package com.gxd.dao.impl;

import com.gxd.dao.AddressDao;
import com.gxd.domain.Address;
import com.gxd.util.DBUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

public class AddressDaoImpl implements AddressDao {
    @Override
    public List<Address> findByUid(int id) {
        QueryRunner queryRunner = new QueryRunner(DBUtils.getDataSource());
        String sql=" select id,detail,name,phone,uid,level from tb_address where uid=?  ";
        try {
            return queryRunner.query(sql,new BeanListHandler<>(Address.class),id);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void addAddress(Address address) {
        QueryRunner queryRunner = new QueryRunner(DBUtils.getDataSource());
        String sql=" insert into tb_address values(?,?,?,?,?,?)  ";
        try {
            Object[] params={address.getId(),address.getDetail(),address.getName(),address.getPhone(),address.getUid(),address.getLevel()};
             queryRunner.update(sql,params);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void deleteById(int id) {
        QueryRunner queryRunner = new QueryRunner(DBUtils.getDataSource());
        String sql=" delete from tb_address where id=? ";
        try {
            queryRunner.update(sql,id);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void updateAddress(Address address) {
        QueryRunner queryRunner = new QueryRunner(DBUtils.getDataSource());
        String sql=" update tb_address set detail=?,name=?,phone=? where id=?  ";
        try {
            Object[] params={address.getDetail(),address.getName(),address.getPhone(),address.getId()};

            queryRunner.update(sql,params);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void clearDefaultAddress(int uid) {
        QueryRunner queryRunner = new QueryRunner();
        Connection connection = DBUtils.getConnection();

        String sql=" update tb_address set level=0 where uid=? ";
        try {
            queryRunner.update(connection,sql,uid);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void setDefaultAddress(String aid) {
        QueryRunner queryRunner = new QueryRunner();
        Connection connection = DBUtils.getConnection();

        String sql=" update tb_address set level=1 where id=? ";
        try {
            queryRunner.update(connection,sql,aid);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
